package org.bigjava.buff.user.web.controller;

import org.bigjava.buff.goods.bean.ExteriorAndPrice;
import org.bigjava.buff.goods.service.GoodsService;
import org.bigjava.buff.user.bean.Deal;
import org.bigjava.buff.user.bean.User;
import org.bigjava.buff.user.service.DealService;
import org.bigjava.buff.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/deal")
public class DealController {

    @Autowired
    private DealService dealService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserService userService;


    //批量上架
    @RequestMapping("/batchPutaway")
    @ResponseBody
    public String batchPutaway(Integer[] epIds, Double[] priceList, HttpServletRequest request){

        User u = (User) request.getSession().getAttribute("userNow");
        List<Deal> dealList = new ArrayList();
        for(int i = 0;i < epIds.length;i++){
            Deal deal = new Deal();
            ExteriorAndPrice ep = new ExteriorAndPrice();
            ep.setId(epIds[i]);
            deal.setEp(ep);
            deal.setUser(u);
            deal.setDealType(1);
            deal.setPrice(priceList[i]);

            deal.setDealTime(new Date());
            dealList.add(deal);
        }

        List sellGoodsList = dealService.batchDeal(dealList);

        return "user/mysell";
    }


    //批量下架饰品
    @RequestMapping("/batchSoldOutGoods")
    @ResponseBody
    public String batchSoldOutGoods(Integer[] dealIds,HttpServletRequest request){

        System.out.println(dealIds.length);

        dealService.batchSoldOutGoods(dealIds);

        return "user/mysell";
    }

    //购买饰品
    @RequestMapping("/buyGoods")
    @ResponseBody
    public String buyGoods(String orderNumber,HttpServletRequest request){
        System.out.println(orderNumber);

        String res;

        Deal deal = dealService.getDealByOrderNum(orderNumber);
        User user = (User)request.getSession().getAttribute("userNow");

        User buyUser = userService.getUserbyId(user.getId()); //购买者的信息
        if(buyUser.getBalance() < deal.getPrice()){
            res = "no";
        } else{
            //更新余额
            userService.updateBalance(buyUser.getId(), deal.getPrice(),-1);
            userService.updateBalance(deal.getUser().getId(),deal.getPrice(),1);
            //修改饰品指向用户
            goodsService.updateGoodsUser(buyUser.getId(), deal.getEp().getId());
            //关闭交易
            dealService.closeDeal(deal.getId());
            res = "ok";
        }
        return res;
    }
}
